package com.mao.controller;

import com.mao.common.lang.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@RestController
@Api(tags = "文件上传")
public class FileUpLoadController {

    @Value("${minio.endpoint}")
    private  String endpointurl;
    @Value("${minio.accesskey}")
    private  String accessKey;
    @Value("${minio.secretkey}")
    private  String secretkey;
    @Value("${minio.bucketName}")
    private  String bucketName;

    /**
     * 上传文件到minio
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传图片返回url")
    public Result uploadFile(MultipartFile file) throws Exception {


            // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpointurl)
                    .credentials(accessKey, secretkey)
                    .build();

            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
            }

            // 文件名字
            String fileName = System.currentTimeMillis() + UUID.randomUUID().toString();
            // 上传文件 已经文件大小
            // file.getContentType() 文件类型
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                            file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            // 返回文件访问路径
            String url = endpointurl + "/" + bucketName + "/" + fileName;
            return Result.succ("上传成功", url);



    }

}
